package com.ciwong.epaper.widget;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatDialog;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.IntensiveReadingResultBean;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.widget.evaluate.SpeechTextView;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.mobilelib.utils.BaseConstants;

import java.io.File;


/**
 * Created by keepon on 2018/6/22.
 */
public class IntensiveReadingDialog extends AppCompatDialog implements View.OnClickListener {
    private SpeechTextView mTvWord;
    private TextView mTvScore, mTvNext, mTvReread;
    private ColorationTextView mTvSymbol;
    private ImageView mIvPlayAudio;
    private RelativeLayout mRlPlayAudio;
    private static final String TAG = "IntensiveReadingDialog";
    private Activity mContext;
    private IntensiveReadingResultBean mIntensiveReadingResultBean;


    public IntensiveReadingDialog(@NonNull Activity context, IntensiveReadingResultBean intensiveReadingResultBean) {
        super(context);
        mContext = context;
        setContentView(R.layout.dialog_reading_intensive);
        Window dialogWindow = getWindow();
        dialogWindow.setBackgroundDrawableResource(R.drawable.shape_dialog_bg);
//		getWindow().setDimAmount(0f);
        setCanceledOnTouchOutside(false);
        setCancelable(false);
        init();
        initEvent();
        //去掉某些系统dialog中会用蓝色的问题
        try {
            int dividerID = context.getResources().getIdentifier("android:id/titleDivider", null, null);
            View divider = findViewById(dividerID);
            divider.setBackgroundColor(Color.TRANSPARENT);
        } catch (Exception e) {
            e.printStackTrace();
        }


        setIntensiveReadingResult(intensiveReadingResultBean);
    }

    public boolean dispatchKeyEvent(KeyEvent event) {

        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                if (event.getAction() != KeyEvent.ACTION_UP && mIntensiveReadingClickListener != null) {
                    mIntensiveReadingClickListener.onIntensiveReadingShowingClickBack();
                }
                break;
            default:
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    private void init() {
        mTvWord = findViewById(R.id.tv_word);
        mTvSymbol = findViewById(R.id.tv_symbol);
        mTvScore = findViewById(R.id.tv_score);
        mTvNext = findViewById(R.id.tv_next_word);
        mTvReread = findViewById(R.id.tv_reread);
        mIvPlayAudio = findViewById(R.id.iv_play_audio);
        mRlPlayAudio = findViewById(R.id.rl_audio);
    }

    private void initEvent() {
        mRlPlayAudio.setOnClickListener(this);
        mTvNext.setOnClickListener(this);
        mTvReread.setOnClickListener(this);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                setPlayBtnState(mIvPlayAudio, false);
            }
        });
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_audio) {
            if (AudioPlayer.getInstance().isPlaying()) {
                AudioPlayer.getInstance().stop();
            }
            if (mIntensiveReadingResultBean != null) {
                String soundUrl = mIntensiveReadingResultBean.getLocalAudioUrl();
                File file = new File(soundUrl);
                if (file == null || !file.exists()) {
                    soundUrl = FileUtil.getReNameFilePath(soundUrl);
                }
                AudioPlayer.getInstance().setOnPlayListener(mOnPlayListener).play(BaseConstants.FILE_PREFIX + soundUrl, true);
            }

        } else if (id == R.id.tv_reread) {
            if (mIntensiveReadingClickListener != null) {
                dismiss();
                mIntensiveReadingClickListener.onIntensiveReadingClickReread();
            }
        } else if (id == R.id.tv_next_word) {
            if (mIntensiveReadingClickListener != null) {
                dismiss();
                mIntensiveReadingClickListener.onIntensiveReadingClickNextWord();
            }
        }
    }


    private OnPlayListener mOnPlayListener = new OnPlayListener() {
        @Override
        public void onReadPlayer(long l, Object o) {

        }

        @Override
        public void onPlayStart(Object o) {
            setPlayBtnState(mIvPlayAudio, true);

        }

        @Override
        public void stop(Object o) {
            setPlayBtnState(mIvPlayAudio, false);
        }

        @Override
        public void onError(int i, Object o) {

            setPlayBtnState(mIvPlayAudio, false);
        }

        @Override
        public void onBuffer(Object o, long l, long l1) {

        }

        @Override
        public void onPlaying(long l, long l1) {

        }
    };

    public void setIntensiveReadingClickListener(IntensiveReadingClickListener intensiveReadingClickListener) {
        mIntensiveReadingClickListener = intensiveReadingClickListener;
    }

    IntensiveReadingClickListener mIntensiveReadingClickListener;

    public void setIntensiveReadingResult(IntensiveReadingResultBean intensiveReadingResultBean) {
        mIntensiveReadingResultBean = intensiveReadingResultBean;
        if (intensiveReadingResultBean != null) {
            EvaluateResult evaluateResult = intensiveReadingResultBean.getEvaluateResult();
            showResultScore(evaluateResult.getScore());
            setSentence(intensiveReadingResultBean.getOriginalSentence());
            if (EApplication.isSymbolColoration) {
                mTvSymbol.setSymbolColoration(evaluateResult, getCurrentOriginSysmbol(intensiveReadingResultBean.getOriginalSentence()));

            } else {
                mTvSymbol.setText(getCurrentOriginSysmbol(intensiveReadingResultBean.getOriginalSentence()));

            }
            setNextButtonText(intensiveReadingResultBean.isTheLastWord());
        }
    }

    private void setSentence(Sentence originalSentence) {
        mTvWord.setSentence(originalSentence, mTvScore, false);
        mTvWord.setTextColor(EApplication.getInstance().getResources().getColor(R.color.repeat_read_gray));

    }

    public interface IntensiveReadingClickListener {
        void onIntensiveReadingClickReread();

        void onIntensiveReadingClickNextWord();

        void onIntensiveReadingShowingClickBack();
    }

    /**
     * 设置播放图标的显示状态
     *
     * @param isShow
     */
    public void setPlayBtnState(ImageView imageView, boolean isShow) {
        Log.e(TAG, "setPlayBtnState: setPlayBtnState");
        if (isShow) {
            Drawable drawable = imageView.getBackground();
            if (drawable != null && drawable instanceof AnimationDrawable) {
                ((AnimationDrawable) drawable).start();
            }

        } else {
            Drawable drawable = imageView.getBackground();
            if (drawable != null && drawable instanceof AnimationDrawable) {
                ((AnimationDrawable) drawable).stop();
            }
            imageView.setBackgroundDrawable(null);
            imageView.setBackgroundResource(R.drawable.play_animation_ls_intensive_read);

        }
    }


    //显示评测结果
    public void showResultScore(float score) {
        int bg;
        int scoreColor;
        try {
            if (score < SpeechUtils.SCORE_2) {
                scoreColor = R.color.score_red;
                bg = R.mipmap.score_red_rep;
            } else if (score < SpeechUtils.SCORE_4) {
                scoreColor = R.color.score_yellow;
                bg = R.mipmap.score_orange_rep;
            } else {
                scoreColor = R.color.score_green_word;
                bg = R.mipmap.score_green_rep;
            }
            if (mTvScore != null) {
                Drawable drawable = mContext.getResources().getDrawable(bg);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                mTvScore.setCompoundDrawables(null, null, null, drawable);
                int changeSocre = (int) score;
                String scoreString = changeSocre + "分 ";
                SpannableString spanString = new SpannableString(scoreString);
                int size = 28;
                if (mContext != null) {
                    size = mContext.getResources().getDimensionPixelSize(R.dimen.dp_17);
                }

                AbsoluteSizeSpan smallBig = new AbsoluteSizeSpan(size);
                int startIndex = scoreString.indexOf("分");
                //				spanString.setSpan(bigSpan, 0, startIndex, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                spanString.setSpan(smallBig, startIndex, spanString.length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                mTvScore.setText(spanString);
                mTvScore.setTextColor(mContext.getResources().getColor(scoreColor));
            }
        } catch (Exception e) {
            e.getStackTrace();
        }

    }


    public String getCurrentOriginSysmbol(Sentence sentence) {
        try {
            if (sentence != null && sentence.getWordDetails() != null && sentence.getWordDetails().size() > 0) {
                WordDetail word = sentence.getWordDetails().get(0);
                String symbol = word.getSymbol();
                if (symbol != null) {
                    if (!symbol.startsWith("[")) {
                        symbol = "[" + symbol;
                    }
                    if (!symbol.endsWith("]")) {
                        symbol += "]";
                    }
                }
                return symbol;
            }


        } catch (Exception e) {
            return "[]";
        }
        return "[]";
    }


    public void setNextButtonText(boolean islast) {
        if (mTvNext != null) {
            if (islast) {
                mTvNext.setText("完成");
            } else {
                mTvNext.setText("下一个");
            }

        }

    }
}
